import wave
import os
import struct
from recorder import recoder

MAX = 10000
templateNum = 10

def ReadMFCFile(filepath):
    fileReader = open(filepath, "rb")
    info = fileReader.read(12)
    infoTuple = struct.unpack('>IIHH', info)
    nframes = infoTuple[0]
    nbytes = infoTuple[2]
    ndim = nbytes / 4
    data = []
    for i in range(0, nframes):
        tempData = struct.unpack('>' + str(ndim) + 'f', fileReader.read(ndim*4))
        data += [tempData]
    return data

def distance(frame1, frame2):
    ndim = len(frame1)
    sum = 0
    for i in range(0, ndim): 
        sum += abs(frame1[i] - frame2[i])
    return sum

def minPath(num1, num2, num3):
    if num1 < num2:
        if num1 < num3:
            return 1
        else:
            return 3
    else:
        if num2 < num3:
            return 2
        else:
            return 3

def DTW(data1, data2): 
    result = [[0 for col in range(len(data2))] for row in range(len(data1))]
    quan = [[0 for col in range(len(data2))] for row in range(len(data1))]
    result[0][0] = 2 * distance(data1[0], data2[0])
    for y in range(0, len(data2)):
        for x in range(0, len(data1)):
            if y == 0:
                if x == 0:
                    result[x][y] = distance(data1[x], data2[y])
                else:
                    result[x][y] = distance(data1[x], data2[y]) + result[x-1][y]
                    quan[x][y] = x
            else:
                if x == 0:
                    result[x][y] = distance(data1[x], data2[y]) + result[x][y-1]
                    quan[x][y] = y
                else:
                    dis = distance(data1[x], data2[y])
                    comp1 = result[x-1][y] + dis
                    comp2 = result[x-1][y-1] + dis * 2
                    comp3 = result[x][y-1] + dis
                    mark = minPath(comp1, comp2, comp3)
                    if mark == 1:
                        result[x][y] = comp1
                        quan[x][y] = quan[x-1][y] + 1
                    elif mark == 2:
                        result[x][y] = comp2
                        quan[x][y] = quan[x-1][y-1] + 2
                    else:
                        result[x][y] = comp3
                        quan[x][y] = quan[x][y-1] + 1
    return result[x-1][y-1] / quan[x][y]

def calculateCorrectRate():
    template = []
    for i in range(1, templateNum+1):
        templateFilePath = os.path.abspath('.') + '\\mfc\\' + str(i) + '-1.mfc'
        templateData = ReadMFCFile(templateFilePath)
        template += [templateData]
    Sum = 0
    correctSum = 0
    for i in range(1, templateNum+1):
        for j in range(2, 6):
            Sum += 1
            min = 100
            minMark = 0
            testFilePath = os.path.abspath('.') + '\\mfc\\' + str(i) + '-' + str(j) + '.mfc'
            testdata = ReadMFCFile(testFilePath)
            for k in range(0, templateNum):
                s = DTW(template[k], testdata)
                if s < min:
                    min = s
                    minMark = k + 1
            # print minMark
            if minMark == i:
                correctSum += 1
    print('percent: {:.2%}'.format(float(correctSum)/float(Sum)))

def RealTime():
    template = []
    for i in range(1, templateNum+1):
        templateFilePath = os.path.abspath('.') + '\\mfc\\' + str(i) + '-1.mfc'
        templateData = ReadMFCFile(templateFilePath)
        template += [templateData]
    r = recoder()
    r.recoder()
    path = os.path.abspath('.') + '\\RealTimeInput\\test.wav'
    r.savewav(path)
    os.system('HCopy.exe -A -D -T 1 -C .\\tr_wav.cfg -S .\\list.scp')
    min = 100
    minMark = 0
    testFilePath = os.path.abspath('.') + '\\RealTimeInput\\test.mfc'
    testdata = ReadMFCFile(testFilePath)
    for k in range(0, templateNum):
        s = DTW(template[k], testdata)
        if s < min:
            min = s
            minMark = k + 1
    print minMark

print 'List: '
print '1. Calculate the rate of correct match.'
print '2. Real time test'
choice = input()
if choice == 1:
    calculateCorrectRate()
elif choice == 2:
    RealTime()
else:
    print 'Quit.'